package com.StarStudio.Controller;

import com.StarStudio.Service.CouponsService;
import com.StarStudio.Service.PanicBuyingCouponsService;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.Entity.*;
import com.ruoyi.common.core.utils.QueryPageUtils;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.redis.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@RestController
@Slf4j
//@RequestMapping("/pb_coupons")
public class PanicBuyingCouponsController {

    @Autowired
    PanicBuyingCouponsService panicBuyingCouponsService;

    @Autowired
    RedisService redisService;

    @Autowired
    CouponsService couponsService;

    /**
     * 带搜索条件分页查询（商家后台端）
     * @param panicBuyingCoupons 抢购优惠券对象
     * @return 结果对象 Result
     */
    @GetMapping("/page")
    public PageResult findPanicBuyingCouponsList(PanicBuyingCoupons panicBuyingCoupons){
        QueryPageUtils.startPage();
        PageInfo pageInfo;
        List<PanicBuyingCoupons> panicBuyingCouponsList;
        long totalRecord;
        try {
            panicBuyingCouponsList = panicBuyingCouponsService.findPanicBuyingCouponsList(panicBuyingCoupons);
            totalRecord = panicBuyingCouponsService.findTotalRecord();
            pageInfo = new PageInfo<>(panicBuyingCouponsList);
        } catch (Exception e) {
            e.printStackTrace();
            return new PageResult(HttpStatusCode.ERROR, MessageConstant.QUERY_PANIC_BUYING_COUPONS_FAIL);
        }
        return new PageResult(HttpStatusCode.SUCCESS,MessageConstant.QUERY_PANIC_BUYING_COUPONS_SUCCESS,pageInfo.getTotal(),panicBuyingCouponsList,totalRecord);
    }

    /**
     * 带搜索条件分页查询（APP端）
     * @param panicBuyingCoupons 抢购优惠券对象
     * @return 结果对象 Result
     */
    @GetMapping("/list")
    public Result findPanicBuyingCouponsResultList(PanicBuyingCoupons panicBuyingCoupons){
        List<PanicBuyingCoupons> panicBuyingCouponsList;
        List<CouponsResult> list = null;
        try {
            panicBuyingCouponsList = panicBuyingCouponsService.findPanicBuyingCouponsList(panicBuyingCoupons);
            if (panicBuyingCouponsList.size() > 0){
                list = new ArrayList<>();
                for (PanicBuyingCoupons pbCoupons : panicBuyingCouponsList) {
                    CouponsResult couponsResult = new CouponsResult(couponsService.findByCouponsId(pbCoupons.getCoupons_id()),pbCoupons);
                    if (new Timestamp(new Date().getTime()).before(pbCoupons.getPanic_buying_start_time())){
                        couponsResult.setRemainBeginSeconds((int)((pbCoupons.getPanic_buying_start_time().getTime() - new Date().getTime())/1000));
                        couponsResult.setRemainEndSeconds((int)((pbCoupons.getPanic_buying_end_time().getTime() - new Date().getTime())/1000));
                    }else if (new Timestamp(new Date().getTime()).after(pbCoupons.getPanic_buying_end_time())) {
                        couponsResult.setRemainBeginSeconds(-1);
                        couponsResult.setRemainEndSeconds(-1);
                    }else {
                        couponsResult.setRemainBeginSeconds(0);
                        couponsResult.setRemainEndSeconds((int)((pbCoupons.getPanic_buying_end_time().getTime() - new Date().getTime())/1000));
                    }
                    list.add(couponsResult);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(HttpStatusCode.ERROR, MessageConstant.QUERY_PANIC_BUYING_GOODS_FAIL);
        }
        return new Result(HttpStatusCode.SUCCESS,MessageConstant.QUERY_PANIC_BUYING_GOODS_SUCCESS,list);
    }


    /**
     * 更新抢购商品信息
     * @param panicBuyingCoupons 抢购优惠券对象
     * @return 结果对象 Result
     */
    @Log(title = "更新抢购优惠券", businessType = BusinessType.UPDATE)
    @PutMapping("/put")
    public Result updatePanicBuyingCoupons(@RequestBody PanicBuyingCoupons panicBuyingCoupons){
        int i;
        try {
            i = panicBuyingCouponsService.updatePanicBuyingCoupons(panicBuyingCoupons);
            if (i > 0){
                // 将抢购商品库存更新到 Redis缓存中
                redisService.setCacheObject("panic_buying_coupons:" + panicBuyingCoupons.getCoupons_id(),panicBuyingCoupons.getPanic_buying_coupons_stock());
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (e.getMessage().equals("商品库存不足！")){
                return new Result(HttpStatusCode.ERROR,MessageConstant.OUT_OF_GOODS_STOCK);
            }
            if (e.getMessage().equals("库存不能小于零！")){
                return new Result(HttpStatusCode.ERROR,MessageConstant.STOCK_CAN_NOT_LESS_THAN_ZERO);
            }
            return new Result(HttpStatusCode.ERROR,MessageConstant.UPDATE_PANIC_BUYING_COUPONS_FAIL);
        }
        return new Result(HttpStatusCode.SUCCESS,MessageConstant.UPDATE_PANIC_BUYING_COUPONS_SUCCESS,i);
    }

    /**
     * 新增抢购优惠券
     * @param panicBuyingCoupons 抢购优惠券对象
     * @return 结果对象 Result
     */
    @Log(title = "新增抢购优惠券",businessType = BusinessType.INSERT)
    @PostMapping("/post")
    public Result AddPanicBuyingCoupons(@RequestBody PanicBuyingCoupons panicBuyingCoupons){
        try {
            panicBuyingCouponsService.AddPanicBuyingCoupons(panicBuyingCoupons);
        } catch (Exception e) {
            e.printStackTrace();
            if (e.getMessage().equals("优惠券库存不足！")){
                return new Result(HttpStatusCode.ERROR,MessageConstant.OUT_OF_COUPONS_STOCK);
            }
            return new Result(HttpStatusCode.ERROR,MessageConstant.ADD_PANIC_BUYING_COUPONS_FAIL);
        }
        return new Result(HttpStatusCode.SUCCESS,MessageConstant.ADD_PANIC_BUYING_COUPONS_SUCCESS);
    }

    /**
     * 删除抢购优惠券
     * @param panic_buying_coupons_id 抢购优惠券对象
     * @return 结果对象 Result
     */
    @Log(title = "删除抢购优惠券",businessType = BusinessType.DELETE)
    @DeleteMapping("/{panic_buying_coupons_id}")
    public Result DeletePanicBuyingCoupons(@PathVariable long panic_buying_coupons_id){
        try {
            panicBuyingCouponsService.DeletePanicBuyingCoupons(panic_buying_coupons_id);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(HttpStatusCode.ERROR,MessageConstant.DELETE_PANIC_BUYING_COUPONS_FAIL);
        }
        return new Result(HttpStatusCode.SUCCESS,MessageConstant.DELETE_PANIC_BUYING_COUPONS_SUCCESS);
    }

    /*
     * 远程调用接口
     */
    @RequestMapping("/findByCouponsId/{id}")
    PanicBuyingCoupons findByCoupons_id(@PathVariable(value = "id") long id){
        return panicBuyingCouponsService.findByCoupons_id(id);
    }

    /*
     * 远程调用接口
     */
    @RequestMapping("/PanicBuyingCouponsList")
    List<PanicBuyingCoupons> PanicBuyingCouponsList(){
        List<PanicBuyingCoupons> panicBuyingCoupons = panicBuyingCouponsService.PanicBuyingCouponsList();
        if (CollectionUtils.isEmpty(panicBuyingCoupons)){
            return null;
        }
        return panicBuyingCoupons;
    }

    @RequestMapping("/findByStatus/{status}")
    List<PanicBuyingCoupons> findByStatus(@PathVariable(value = "status") int status){
        List<PanicBuyingCoupons> byStatus = panicBuyingCouponsService.findByStatus(status);
        if (CollectionUtils.isEmpty(byStatus)){
            return null;
        }
        return byStatus;
    }











}
